package com.tchy.cloud.controller;

import com.tchy.cloud.entity.ACustomerEntity;
import com.tchy.cloud.entity.AOfficialWhEntity;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.jboss.logging.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.tcdev.entity.TArticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 文章管理
 * Created by zjy on 2015/9/22.
 */
@Controller
@RequestMapping("/officialWhController")
public class OfficialWhController {

    private static final Logger logger = Logger.getLogger(OfficialWhController.class);

    @Autowired
    private SystemService systemService;

    private String message;


    /**
     * 文章管理列表页
     * @return
     */
    @RequestMapping(params = "officialWhList")
    public ModelAndView officialWhList(){
        return new ModelAndView("clound/articleManager/officialWh/officialWhList");
    }


    /**
     * 文章管理列表
     * @param officialWh
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagrid")
    public void partnerApplyDatagrid(AOfficialWhEntity officialWh, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid){
        CriteriaQuery cq = new CriteriaQuery(AOfficialWhEntity.class,dataGrid);

        String column = request.getParameter("columns");//栏目名称, 多个以,分隔
        if(StringUtil.isNotEmpty(column)){
            String[] columnStr = column.split(",");
            List<String> columnIds = new ArrayList<String>();
            for(String cName : columnStr){
                List<String> tempIds = this.systemService.findByQueryString("select c.id from AColumns c where c.deleted = 0 " +
                        "and c.enable = 1 and c.title = '" + cName.trim() + "'");
                columnIds.addAll(tempIds);
            }

            if(columnIds.size() == 0 && columnStr.length > 0){

                columnIds.add(columnStr[0]);

            }

            List<SimpleExpression> list = new ArrayList<SimpleExpression>();
            for(int i = 0; i < columnIds.size(); i++){
               list.add(Restrictions.like("factorColumn","%|" + columnIds.get(i) + "|%"));
            }
            if(list.size() > 0){
                cq.or(Restrictions.or(list.get(0)),Restrictions.or(list.toArray(new SimpleExpression[]{})));
            }
        }

        Map<String,Object> orderMap = new HashMap<String,Object>();
        orderMap.put("writeTime","desc");
        orderMap.put("status","asc");

        cq.setOrder(orderMap);
//        cq.addOrder("status",SortDirection.asc);
//        cq.addOrder("writeTime",SortDirection.desc);
        cq.eq("deleted",0);
        cq.add();

        // 查询条件组装
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, officialWh, request.getParameterMap());
        this.systemService.getDataGridReturn(cq,true);

        List owList = dataGrid.getResults();

        for(int i = 0; i < owList.size(); i++){

            AOfficialWhEntity officialWh1 = (AOfficialWhEntity)owList.get(i);
            //翻译
            List<String> columnName = systemService.findListbySql(
                    "select t2.title from a_official_columns t1 \n" +
                            "left join a_columns t2 on t1.columns_id = t2.columns_id \n" +
                            "where t1.article_id = " + officialWh1.getArticleId());

            officialWh1.setFactorColumnName(StringUtil.listToStringSlipStr(columnName,","));

        }

        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 跳转到修改转视图
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(AOfficialWhEntity officialWh,
                                    HttpServletRequest req) {


        if (StringUtil.isNotEmpty(officialWh.getArticleId())) {
            officialWh = systemService.getEntity(AOfficialWhEntity.class, officialWh.getArticleId());

            //翻译
            List<String> columnIds = systemService.findListbySql(
                    "select t2.columns_id from a_official_columns t1 \n" +
                            "left join a_columns t2 on t1.columns_id = t2.columns_id \n" +
                            "where t1.article_id = " + officialWh.getArticleId());

            req.setAttribute("officialWh", officialWh);
            req.setAttribute("columnIds", columnIds);

        }


        return new ModelAndView("clound/articleManager/officialWh/officialWh");
    }

    /**
     * 添加文章管理
     *
     * @param officialWh
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson save(AOfficialWhEntity officialWh, HttpServletRequest request) {

        AjaxJson j = new AjaxJson();
        if (officialWh.getArticleId() != null) {

            try {

                AOfficialWhEntity c = systemService.get(AOfficialWhEntity.class, officialWh.getArticleId());
                MyBeanUtils.copyBeanNotNull2Bean(officialWh, c);
                c.setCustomerEntity(systemService.get(ACustomerEntity.class, 101));
                systemService.saveOrUpdate(c);
                message = "修改文章《" + officialWh.getTitle() + "》成功";

            } catch (Exception e) {
                e.printStackTrace();
                message = "修改文章《" + officialWh.getTitle() + "》失败";

            }
        } else {

                TSUser user = ResourceUtil.getSessionUserName();

            try {

                officialWh.setCreateTime(new Date());
                officialWh.setDeleted(0);
                officialWh.setCommentNum(0);
                officialWh.setPraiseNum(0);
                officialWh.setReadNum(0);
                officialWh.setWriteTime(new Date());
                officialWh.setEditorType(11);
                officialWh.setEditor(user);
                officialWh.setStatus(0);//待审核
                officialWh.setSourceAvatar("upload/sourceAvatar.jpg");//默认头像

                systemService.save(officialWh);

                String columnIds = request.getParameter("columnIds");

                if(StringUtil.isNotEmpty(columnIds)){

                    String addCidSQL = "insert into a_official_columns values(?,?)";
                    List<String> columnIdList = StringUtil.splitToList(",",columnIds);
                    for(String cid : columnIdList){

                        if(StringUtil.isNotEmpty(cid)){

                            systemService.executeSql(addCidSQL,new Object[]{Long.parseLong(cid),officialWh.getArticleId()});

                        }
                    }

                }

                message = "保存文章《" + officialWh.getTitle() + "》成功";
            } catch (Exception e) {
                e.printStackTrace();

                message = "保存文章《" + officialWh.getTitle() + "》失败";
            }



        }
        systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }


    /**
     * 删除正式文章（逻辑删除）
     * @param id
     * @return
     */
    @RequestMapping(params = "delOfficialWh")
    @ResponseBody
    public AjaxJson delOfficialWh(String id){
        AjaxJson j = new AjaxJson();
        try {

            AOfficialWhEntity officialWh = systemService.get(AOfficialWhEntity.class,Long.valueOf(id));

            if(officialWh != null){
                officialWh.setDeleted(1);
                systemService.saveOrUpdate(officialWh);
                message = "删除文章《"+officialWh.getTitle()+"》成功";
            }else{
                message = "文章信息不存在，请刷新重试！";
            }


        } catch (Exception e) {

            message = "删除正式文章失败";
        }

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }

    /**
     * 预览
     * @param articleId
     * @param request
     * @return
     */
    @RequestMapping(params = "getOfficialWh")
    public ModelAndView getOfficialWh(Long articleId, HttpServletRequest request){
        AOfficialWhEntity wh = systemService.get(AOfficialWhEntity.class, articleId);
        request.setAttribute("source",wh.getSource());
//        if(13 == wh.getArticleType()){//视频
//            List<AOfficialMedia> lists = systemService.findByProperty(AOfficialMedia.class, "officialWh.articleId", articleId);
//            if(!ListUtils.isNullOrEmpty(lists)){
//                request.setAttribute("path", lists.get(0).getPath());
//                request.setAttribute("format", wh.getArticleType());
//            }
//        }else if(12 == wh.getArticleType()){//图片
//            request.setAttribute("format", wh.getArticleType());
//            List<AOfficialMedia> lists = systemService.findByProperty(AOfficialMedia.class, "officialWh.articleId", articleId);
//            request.setAttribute("pics", lists);
//        }else{//图文
            request.setAttribute("content", wh.getContent());
            request.setAttribute("format", wh.getArticleType());
//        }

        return new ModelAndView("clound/articleManager/officialWh/previewOfficialWh");
    }


    /**
     * 原创文章库多媒体列表页
     * @return
     */
    @RequestMapping(params = "player")
    public ModelAndView player(String path,String source, HttpServletRequest request){


        request.setAttribute("path",path);
        request.setAttribute("source",source);

        return new ModelAndView("clound/articleManager/officialWh/officialMedia/player");
    }

    /**
     * 选择专题列表
     *
     * @return
     */
    @RequestMapping(params = "miniSpecialList")
    public ModelAndView miniSpecialList(String articleId, HttpServletRequest request) {
        request.setAttribute("articleId", articleId);

        return new ModelAndView("clound/articleManager/officialWh/special/miniSpecialList");
    }


    /**
     * 查询配置的预览通知信息
     * @return
     */
    @RequestMapping(params = "findArticleNotice")
    @ResponseBody
    public AjaxJson findArticleNotice(){
        AjaxJson j = new AjaxJson();

        String msg = "";

        try {

            //预览通知信息固定ID 29
            TArticle article = systemService.get(TArticle.class,"29");

            msg = article.getContents();
            j.setSuccess(true);
        } catch (Exception e) {
            j.setSuccess(false);
            msg = "查询预览配置信息失败";
        }

        j.setMsg(msg);
        return j;
    }


    /**
     * 审核文章
     * @param id
     * @return
     */
    @RequestMapping(params = "statusOfficialWh")
    @ResponseBody
    public AjaxJson statusOfficialWh(String id,Integer status){
        AjaxJson j = new AjaxJson();
        try {

            AOfficialWhEntity officialWh = systemService.get(AOfficialWhEntity.class,Long.valueOf(id));

            if(officialWh == null){

                message = "文章信息不存在，请刷新重试！";
                j.setMsg(message);
                return j;
            }

            if(officialWh.getStatus() != 0){

                message = "文章《"+officialWh.getTitle()+"》已被审核,不能重复审核!";
                j.setMsg(message);
                return j;
            }
            TSUser user = ResourceUtil.getSessionUserName();

            if(status == 1){//通过

                officialWh.setPublisher(user);
                officialWh.setPublishTime(new Date());

                message = "文章《"+officialWh.getTitle()+"》审核通过";

            }else{//不通过
                status = 2;
                message = "文章《"+officialWh.getTitle()+"》审核不通过";
            }

            officialWh.setStatus(status);
            systemService.saveOrUpdate(officialWh);


        } catch (Exception e) {

            message = "删除正式文章失败";
        }

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }

}
